import React, { Component } from 'react'
import { ScrollView, View } from '@tarojs/components'

import Placeholder from '@/src/components/placeholder'
import Page from '@/src/components/page'
import GoodsList from './components/goods-list'
import GoodsInvalidList from './components/goods-invalid-list'
import PayBar from './components/pay-bar'

import { connect } from 'react-redux'
import { State } from '@/src/dva/state'
import { CartState } from '@/src/dva/models/cart'

import Taro from '@tarojs/taro'
// import Api from '@/src/lib/api/api'
import Global from '@/src/lib/global'
import SheetCoupon from '@/src/components/sheet-get-coupon'
import { EventKey } from '@/src/consts'
import ServiceBtn from '@/src/components/service-btn'
import { TempState } from '@/src/dva/models/temp'


import { MovableArea, MovableView } from '@tarojs/components';
import './index.scss'

interface ShopcartProps {
    cart: CartState
    temp: TempState
    dispatch: any
}

interface ShopcartState {
    coupontip: string,
    couponPrice: number
}

class Shopcart extends Component<ShopcartProps, ShopcartState> {

    isFirstShow = true
    totalSelectedPrice: number
    couponGetSheetRef = React.createRef<SheetCoupon>()

    constructor(props) {
        super(props)
        this.state = {
            coupontip: "",
            couponPrice: 0
        }
    }

    onLoad() {
        Taro.eventCenter.on(EventKey.LoginStatusChange, this.onLoginStatusChange)
        Taro.eventCenter.on(EventKey.OrderConfirm, this.onOrderConfirm)
    }

    onUnload() {
        Taro.eventCenter.off(EventKey.LoginStatusChange, this.onLoginStatusChange)
        Taro.eventCenter.on(EventKey.OrderConfirm, this.onOrderConfirm)
    }

    onLoginStatusChange = () => {
        if (Global.isLogin()) {
            this.requestData().then(() => {
                this.toggleAllSelect(true)
            })
        } else {
            this.setState({
                coupontip: ""
            })
        }
    }

    onOrderConfirm = () => {
        this.totalSelectedPrice = 0
    }

    componentDidShow = () => {
        if (Global.isLogin()) {
            this.requestData().then(() => {
                if (this.isFirstShow) {
                    this.isFirstShow = false
                    this.toggleAllSelect(true)
                }
            })
        }
    }

    requestData = async () => {
        const { dispatch } = this.props
        await dispatch({
            type: "cart/getCartList",
        })
    }


    toggleAllSelect = (isSelectAll?: boolean) => {
        const { cart, temp, dispatch } = this.props
        if (cart.goodsList.length <= 0) {
            return
        }

        if (!isSelectAll) {
            isSelectAll = cart.goodsList.length != temp.shopcart.selectedGoodsIds.size
        }

        if (isSelectAll) {
            dispatch({
                type: "temp/shopcartInsertSelectedGoodsId",
                payload: cart.goodsList.map((v) => v.goodsid)
            })
        } else {
            dispatch({
                type: "temp/shopcartClearSelectedGoodsId",
                payload: cart.goodsList.map((v) => v.goodsid)
            })
        }
    }

    onAllSelectBtnClick = () => {
        this.toggleAllSelect()
    }

    onDeleteBtnClick = () => {
        const { dispatch } = this.props

        Taro.showModal({
            content: "确认将宝贝删除嘛？",
            success: (res) => {
                if (res.confirm) {

                    const { temp } = this.props
                    let goodsIds = Array.from(temp.shopcart.selectedGoodsIds)

                    dispatch({
                        type: "cart/removeGoods",
                        payload: goodsIds
                    })
                }
            }
        })
    }

    onPlaceholderBtnClick = () => {
        Taro.switchTab({ url: "/pages/home/index" })
    }

    /**
     * 请求可用的优惠券信息
     */
    //   requestCouponInfo = () => {
    //     if (!Global.isLogin()) {
    //       return
    //     }

    //     Api.goodsCartGetCouponInfo({
    //       totalprice: this.totalSelectedPrice
    //     }).then((res) => {
    //       console.log(res)
    //       if (!Api.handleResponse(res)){
    //         return
    //       }
    //       this.setState({
    //         coupontip: res?.data.coupontip,
    //         couponPrice: res?.data.orderprice,
    //       })
    //     })
    //   }

    onGetCouponBtnClick = () => {
        let sheet = this.couponGetSheetRef.current
        if (sheet) {
            sheet.requestCouponList().then(ret => {
                if (ret) {
                    sheet?.show()
                }
            })
        }
    }


    onConfirmBtnClick = () => {
        const { cart, temp } = this.props
        if (temp.shopcart.selectedGoodsIds.size <= 0) {
            Global.showToast("请选择结算商品")
            return
        }

        let models = new Array()
        for (const goodsId of temp.shopcart.selectedGoodsIds) {
            for (const model of cart.goodsList) {
                if (model.goodsid == goodsId) {
                    models.push(model)
                    break
                }
            }
        }

        Global.navigateTo("/pages/order-confirm/index", {
            package: "subpackages",
            params: {
                models: models,
                isFromCart: true
            }
        })
    }

    render() {
        const { cart, temp } = this.props

        let goodsList = cart.goodsList ?? []
        let invalidGoodsList = cart.invalidGoodsList ?? []
        console.log('goodsList', goodsList)
        // console.log('invalidGoodsList', invalidGoodsList)
        let totalPrice = 0
        let totalNum = 0
        for (const goodsId of temp.shopcart.selectedGoodsIds) {
            for (const model of cart.goodsList) {
                // const realprice =  model.realprice;
                if (goodsId == model.goodsid) {
                    /**
                     * 1、判断是否有goodsprice
                     * 2、判断是否有活动价格
                     */
                    if (model.goodsprice) {
                        totalNum += Number.parseInt(model.num)
                        totalPrice += Number.parseFloat(model.goodsprice) * Number.parseInt(model.num);
                        console.log('totalPrice', totalPrice)
                    } else {
                        if (Number.parseFloat(model.activityprice) > 0) {
                            console.log('model.activityprice')
                            totalNum += Number.parseInt(model.num)
                            totalPrice += Number.parseFloat(model.activityprice) * Number.parseInt(model.num);
                            // console.log('totalPrice',totalPrice)
                        } else {
                            console.log('sssss')
                            totalNum += Number.parseInt(model.num)
                            totalPrice += Number.parseFloat(model.realprice) * Number.parseFloat(model.num)
                        }
                    }




                    // if (Number.parseFloat(model.activityprice)>0) {
                    //     if(model.goodsprice){
                    //         totalNum += Number.parseInt(model.num)
                    //         totalPrice += Number.parseFloat(model.goodsprice) * Number.parseInt(model.num);
                    //         console.log('totalPrice',totalPrice)
                    //     }else{
                    //         console.log('ssss')
                    //         totalNum += Number.parseInt(model.num)
                    //         totalPrice += Number.parseFloat(model.activityprice) * Number.parseInt(model.num);
                    //         console.log('totalPrice',totalPrice)
                    //     }
                    // } else {
                    //     console.log('sssss')
                    //     totalNum += Number.parseInt(model.num)
                    //     totalPrice += Number.parseFloat(model.realprice) * Number.parseFloat(model.num)

                    // }
                    // model.oldRealprice  =realprice 
                    break
                }
            }
        }

        if (this.totalSelectedPrice != totalPrice) {
            this.totalSelectedPrice = totalPrice
            //   this.requestCouponInfo()
        }

        let el: JSX.Element
        if (goodsList.length <= 0 && invalidGoodsList.length <= 0) {
            el = <Placeholder desc="购物车还空着呢~\n买点什么犒劳自己吧~" button="立刻逛逛" onBtnClick={this.onPlaceholderBtnClick} />
        } else {

            let children = new Array()
            if (goodsList.length > 0) {
                children.push(<GoodsList
                    models={goodsList}
                    discountTip={this.state.coupontip}
                    isExistDiscount={this.state.couponPrice > 0}
                    isShowPickBtn={totalNum > 0}
                    onGetCouponBtnClick={this.onGetCouponBtnClick}
                />)
            }

            if (invalidGoodsList.length > 0) {
                children.push(<GoodsInvalidList models={invalidGoodsList} />)
            }


            el = (
                <View style={{ position: "relative", height: "100%" }}>
                    <ScrollView className="scrollview" scrollY enhanced showScrollbar={false}>
                        <View className="scrollview-content">
                            {children}
                        </View>
                    </ScrollView>

                    <PayBar
                        isAllSelected={cart.goodsList.length == temp.shopcart.selectedGoodsIds.size && cart.goodsList.length > 0}
                        onAllSelectBtnClick={this.onAllSelectBtnClick}
                        selectedNum={totalNum}
                        totoalPrice={totalPrice}
                        onDeleteBtnClick={this.onDeleteBtnClick}
                        onConfirmBtnClick={this.onConfirmBtnClick}
                    />

                    <SheetCoupon ref={this.couponGetSheetRef} />
                </View>
            )
        }

        return (
            <Page navigationBar={{ title: "购物车" }} fixed>
                <MovableArea style=' width: 100%; height: 100%;'>
                    {el}
                    <MovableView x="350" y="500" direction="all" className="movab1">
                        <ServiceBtn />
                    </MovableView>

                </MovableArea>
            </Page>
        )
    }
}


export default connect((state: State) => ({ cart: state.cart, temp: state.temp }))(Shopcart)